import * as fs from 'fs'
import * as step from '@flow-step/step-toolkit'
import * as util from './util'

export function getUser(
    type: string | undefined,
    hostGitUserName: string | undefined
): string | undefined {
    if (type === undefined) {
        step.error(
            "Get repository type failed, can not resolve repo type from 'TYPE'"
        )
        throw new Error('resolve repo type failed')
    }
    switch (type) {
        case 'aliyun':
            if (process.env['GIT_USERNAME'] != undefined) {
                return process.env['GIT_USERNAME']
            }
            return ''
        case 'gitee':
            if (process.env['GITEE_USERNAME'] != undefined) {
                return process.env['GITEE_USERNAME']
            }
            return ''
        case 'git':
            return hostGitUserName
        case 'customGitlab':
            return hostGitUserName
        default:
            return hostGitUserName
    }
}

export function getHttpPolicy(
    gitRepo: string ,
    type: string 
): string {
    let httpPolicy = 'http'
    if (gitRepo.startsWith('https://') || type === 'aliyun' || type === 'gitee' || type === 'bitbucket' ) {
        httpPolicy = 'https'
    }
    return httpPolicy
}


export function getPassword(
    type: string | undefined,
    hostGitPassword: string | undefined
): string | undefined {
    if (type === undefined) {
        step.error(
            "Get repository type failed, can not resolve repo type from 'TYPE'"
        )
        throw new Error('resolve repo type failed')
    }
    switch (type) {
        case 'aliyun':
            if (process.env['GIT_PRIVATE_TOKEN'] != undefined) {
                return process.env['GIT_PRIVATE_TOKEN']
            }
            return ''
        case 'gitee':
            if (process.env['GITEE_ACCESS_TOKEN'] != undefined) {
                return process.env['GITEE_ACCESS_TOKEN']
            }
            return ''
        case 'git':
            return hostGitPassword
        case 'customGitlab':
            return hostGitPassword
        default:
            return hostGitPassword
    }
}

export function getCloneUrl(
    user: string | undefined,
    password: string | undefined,
    gitRepo: string,
    hostGitMethod: string,
    httpPolicy: string,
    gitEndpoint: string
): string {
    let cloneUrl = gitRepo
    if (hostGitMethod === 'http') {
        if (
            user === undefined ||
            user === '' ||
            password === undefined ||
            password === ''
        ) {
            cloneUrl = httpPolicy + '://' + gitEndpoint
        } else {
            cloneUrl =
                httpPolicy + '://' + encodeURIComponent(user) + ':' + encodeURIComponent(password) + '@' + gitEndpoint
        }
    } else if (hostGitMethod === 'ssh') {
        if (!gitRepo.startsWith('git') && !gitRepo.startsWith('ssh')) {
            step.info(`end point: ${gitEndpoint}`)
            cloneUrl = convertTogit(gitEndpoint)
            step.info(`convert to git: ${cloneUrl}`)
        }
    }
    return cloneUrl
}

export function writePrivateKey(path: string, filename: string, privateKey: string) {
    if (fs.existsSync(path)) {
        util.clearDir(path)
    } else {
        fs.mkdirSync(path)
    }

    const privateKeyFilePath = `${path}${util.SEP}${filename}`
    fs.writeFileSync(privateKeyFilePath, privateKey)
    fs.chmodSync(privateKeyFilePath, 0o400)
    step.info(`Write SSH private key to ${privateKeyFilePath} success`)
}

export function getGitEndpoint(gitRepo: string) {
    let gitEndpoint = ''
    if (gitRepo.startsWith('http://')) {
        gitEndpoint = gitRepo.substring(7, gitRepo.length)
    } else if (gitRepo.startsWith('https://')) {
        gitEndpoint = gitRepo.substring(8, gitRepo.length)
    } else if (gitRepo.startsWith('git@')) {
        gitEndpoint = gitRepo.substring(4, gitRepo.length).replace(/:/g, '/')
    }
    return gitEndpoint
}

export function convertTogit(gitEndpoint: string) {
    let items = gitEndpoint.split('/')
    let result = ''
    for (let i = 0; i < items.length; i++) {
        if (i === 0) {
            result = items[0] + ':'
        } else if (i === 1) {
            result += items[1]
        } else {
            result += '/' + items[i]
        }
    }
    return 'git@' + result
}

export function getHost(url: string | undefined): string | undefined {
    if (url === undefined) {
        return undefined
    }
    let searchResult = url.match('https?://([^/]+).+')
    if (searchResult != null) {
        const httpGitHost: string = searchResult[1]
        return httpGitHost
    } else {
        searchResult = url.match('git@([^/:]+).+')
        if (searchResult != null) {
            const gitHost = searchResult[1]
            return gitHost
        }
        return undefined
    }
}
